import React from 'react'
import { connect } from 'dva'
import { Button, Form, Input, Radio, Checkbox, Row, Col, Icon, Modal, Tree, message, TreeSelect } from 'antd'
import Header from '../../../components/Header/index'
import styles from './AddEmployee.less'
import propTypes from 'prop-types'
import gql from 'graphql-tag'
import { GQL } from '../../../components/GQL/index'
const RadioGroup = Radio.Group
const { TreeNode } = Tree
const Save = ({ editStaff, validateFieldsAndScroll, staff, ruleGroupIds }) => {
  return <Button onClick={() => save(editStaff, validateFieldsAndScroll, staff, ruleGroupIds)} type='primary'>确定</Button>
}
const SaveAGQL = GQL({
  mutation: gql`
    mutation editStaff($staff: StaffInput!){
      editStaff(staff: $staff){
        status
        message
      }
    }
  `,
  name: 'editStaff'
})(Save)

function save (editStaff, validateFieldsAndScroll, { staffId }, ruleGroupIds) {
  validateFieldsAndScroll((err, data) => {
    if (!err) {
      staffId && (data.staffId = parseInt(staffId))
      editStaff({ variables: { staff: data } }).then(({ data: { editStaff } }) => {
        const { status } = editStaff
        if (status === null) {
          message.error(editStaff.message)
          return
        }
        message.success(editStaff.message)
      }).catch(err => {
        console.log(err)
      })
    }
  })
}

function AddEmployee ({ match, loading, data, employeeAcount, dispatch, updateQuery, form: { getFieldDecorator, validateFieldsAndScroll } }) {
  // 获取区域数据
  const { area = [], permissions = [], permissionGroups = [], accountInfo = {} } = data
  // const { staff } = employeeAcount
  const { staff = {} } = accountInfo

  // 获取部门数据
  const { departments = [] } = data
  const headerData = {
    title: staff.staffId ? '修改账号' : '新增员工',
    hasSubNav: true,
    subNavItem: [
      { title: '首页', link: true }, { title: '员工账号', link: true },
      { title: '员工账号', link: false }, { title: '员工账号', link: true }
    ]
  }
  const changeSelectStatus = (item = []) => {
    let arr = []
    const permisessionItems = permissionGroups.filter(t => item.indexOf(t.groupId) !== -1)
    permisessionItems.forEach(t => { arr = [...arr, ...t.ruleGroupIds] })
    arr = Array.from(new Set(arr))
    updateQuery((previousResult, { variables }) => {
      let { permissions = [] } = previousResult
      permissions.forEach((t, k) => {
        permissions[k].status = arr.indexOf(t.ruleGroupId) !== -1
        permissions[k].children && permissions[k].children.forEach((_t, _k) => {
          permissions[k].children[_k].status = arr.indexOf(_t.ruleGroupId) !== -1
        })
      })
      return previousResult
    })
  }

  function onSelect (e) {
    // console.log(e.target.value)
    if (e.target.value !== 'indoorwork') {
      dispatch({
        type: 'employeeAcount/staffType',
        payload: e.target.value
      })
    } else {
      dispatch({
        type: 'employeeAcount/staffType',
        payload: 'indoorwork'
      })
    }
  }
  const AREA = data => data.map((item) => {
    if (item.children && item.children.length) {
      return <TreeNode key={item.value} title={item.name}>{AREA(item.children)}</TreeNode>
    }
    return <TreeNode key={item.value} title={item.name} />
  })

  const getCheckedIds = () => {
    let ids = []
    permissions.map((t, k) => {
      if (t.status) { ids = [...ids, t.ruleGroupId] }
      if (t.children) {
        t.children.map(_t => {
          if (_t.status) { ids = [...ids, _t.ruleGroupId] }
        })
      }
    })
    return ids
  }

  return (
    <div>
      <Header header={headerData} />
      <div className={styles.center}>
        <div className={styles.center1}>
          <h2>账号信息</h2>
          <Form>
            <Form.Item label='登录账号' required>
              {
                getFieldDecorator('accountsName', { initialValue: staff.accountsName ? staff.accountsName : '' })(
                  <Input placeholder='只能包括英文字母、数字、支持Email' />
                )
              }
            </Form.Item>
            <Form.Item label='密码' required>
              { staff.staffId
                ? <a >修改密码</a> : getFieldDecorator('pwd', { initialValue: '' })(
                  <Input type='password' />
                )
              }
            </Form.Item>
            <Form.Item label='身份'>
              { getFieldDecorator('staffType', { initialValue: staff.staffId ? staff.staffType : 'indoorwork' })(
                <RadioGroup onChange={onSelect}>
                  <Radio value='indoorwork' defaultChecked>内勤</Radio>
                  <Radio value='salesman'>业务员</Radio>
                  <Radio value='boss'>老板</Radio>
                  <Radio value='driver'>司机</Radio>
                </RadioGroup>
              )
              }
            </Form.Item>
            <Form.Item label='姓名' required>
              {
                getFieldDecorator('staffName', { initialValue: staff.staffName ? staff.staffName : '' })(
                  <Input />
                )
              }
            </Form.Item>
            <Form.Item label='职位'>
              {
                getFieldDecorator('title', { initialValue: staff.title ? staff.title : '' })(
                  <Input />
                )
              }
            </Form.Item>
            <Form.Item label='部门'>
              {
                getFieldDecorator('branchId', { initialValue: staff.branchName ? staff.branchName : 0 })(
                  <TreeSelect
                    treeData={departments.map(item => {
                      return { value: item.id, title: item.name }
                    })}
                    placeholder='请选择部门'
                    onChange={(value) => dispatch({ type: 'employeeAcount/save', payload: { value } })}
                  />)
              }
            </Form.Item>
            <Form.Item label='备注'>
              {
                getFieldDecorator('remark', { initialValue: staff.remark ? staff.remark : '' })(
                  <Input.TextArea rows={3}></Input.TextArea>
                )
              }
            </Form.Item>
            <Form.Item label='手机号' required>
              {
                getFieldDecorator('mobile', { initialValue: staff.mobile ? staff.mobile : '' })(
                  <Input placeholder='该手机号码将用于找回密码' />
                )
              }
            </Form.Item>
            <Form.Item label='邮箱'>
              {
                getFieldDecorator('email', { initialValue: '' })(
                  <Input />
                )
              }
            </Form.Item>
            <Form.Item label='QQ'>
              {
                getFieldDecorator('qq', { initialValue: '' })(
                  <Input />
                )
              }
            </Form.Item>
            <Form.Item label='企业微信号'>
              <Input />
            </Form.Item>
          </Form>
        </div>
        <div className={styles.center2}>
          <h2>权限范围</h2>
          <Form>
            <Form.Item label='数据权限'>
              {
                getFieldDecorator('custom', { initialValue: 0 })(
                  <RadioGroup disabled={employeeAcount.staffType !== 'indoorwork'} onChange={() => dispatch({ type: 'employeeAcount/save', payload: { dataPermission: !employeeAcount.dataPermission } })}>
                    {employeeAcount.staffType === 'salesman' ? <span><a><Icon type='plus' />请选择负责的客户</a></span>
                      : <span>
                        <Radio value={0}>全部区域</Radio>
                        <Radio value={1}>部分区域</Radio>
                        { employeeAcount.dataPermission ? <a onClick={() => dispatch({ type: 'employeeAcount/save', payload: { dataModalStatus: true } })}><Icon type='plus' />选择客户区域范围</a> : '' }</span>
                    }
                  </RadioGroup>
                )
              }
              <Modal visible={employeeAcount.dataModalStatus}
                onOk={() => dispatch({ type: 'employeeAcount/save', payload: { dataModalStatus: false } })}
                onCancel={() => dispatch({ type: 'employeeAcount/save', payload: { dataModalStatus: false } })}
                title='选择客户区域范围'
              >
                {
                  getFieldDecorator('areaIds', { initialValue: '' })(
                    <Tree checkable>
                      {AREA(area)}
                    </Tree>
                  )
                }
              </Modal>
            </Form.Item>
            <Form.Item label='角色权限' required>
              {
                getFieldDecorator('groupIds')(
                  <Checkbox.Group onChange={params => changeSelectStatus(params)}>
                    { permissionGroups.map((item, index) =>
                      <Checkbox key={index} value={item.groupId}>{item.groupName}</Checkbox>
                    )}
                  </Checkbox.Group>
                )
              }

              <div className={styles.checkboxDesc}>注意请勾选此账号属于的【角色权限】，对应的【权限明细】即可选中;<br />
              如果您还未设置过【角色权限】，请先<a>设置角色</a>，比如：仓库管理员、财务管理员、业务管理员</div>
            </Form.Item>
            <Form.Item label='权限明细' className={styles.permission}>
              {
                permissions.map((t, i) => {
                  return (
                    <div className={styles.items} key={`permission-check-group-${i}`}>
                      <Row>
                        <Col span={2}>
                          <Checkbox disabled checked={t.status === true}>{ t.ruleGroupName }</Checkbox>
                        </Col>
                        <Col span={20}>
                          <Row>
                            {
                              t.children && t.children.map((_t, _k) => <Col span={8} key={`permisession-check-${i}-${_k}}`}><Checkbox disabled checked={_t.status === true}>{_t.ruleGroupName}</Checkbox></Col>)
                            }
                          </Row>
                        </Col>
                      </Row>
                    </div>
                  )
                })
              }
            </Form.Item>
          </Form>
        </div>
      </div>
      <div className={styles.footer}>
        <SaveAGQL validateFieldsAndScroll={validateFieldsAndScroll} ruleGroupIds={() => getCheckedIds()} staff={staff} />
        <Button>取消</Button>
      </div>
    </div>
  )
}

AddEmployee.propTypes = {
  loading: propTypes.bool,
  data: propTypes.object,
  employeeAcount: propTypes.object,
  dispatch: propTypes.func,
  updateQuery: propTypes.func,
  form: propTypes.object,
  staff: propTypes.object,
  match: propTypes.object
}
Save.propTypes = {
  editStaff: propTypes.func,
  validateFieldsAndScroll: propTypes.func,
  staff: propTypes.object,
  ruleGroupIds: propTypes.func
}
const mapStateToProps = ({ employeeAcount }) => ({ employeeAcount })

const AddEmployeeAGQL = ({ variables }) => {
  const Component = GQL({
    query: gql`
      query accountInfo($accountsId: Int){
        accountInfo(accountsId: $accountsId) {
          staff {
            staffId
            staffName
            title
            mobile
            staffType
          }
        }

        permissionGroups {
          groupId
          groupName
          ruleGroupIds
          isAdministrator
        }
        permissions {
          ruleGroupId
          ruleGroupName
          status
          children {
              ruleGroupId
              ruleGroupName
              status
          }
        }
        departments {
          id
          name
          children {
              id
              name
              children {
                  id
                  name
              }
          }
        }
        area {
          name
          value
          children {
              name
              value
              children {
                  name
                  value
              }
          }
        }
      }
    `,
    variables
  })(connect(mapStateToProps)(Form.create()(AddEmployee)))

  return <Component />
}

AddEmployeeAGQL.propTypes = {
  variables: propTypes.object
}

const AddEmployeeView = ({ match }) => {
  // const accountId =
  console.log(match)
  return <AddEmployeeAGQL variables={{ accountsId: parseInt(match.params.staffId) }} />
}

AddEmployeeView.propTypes = {
  match: propTypes.object
}

export default AddEmployeeView
